<template>
    <a-layout>
      <a-layout-header class="header">
        <!-- Logo 区域 -->
        <div class="logo">
          <img src="@/assets/AIOLogo.png" alt="OceanBase Logo" />
          <span class="artistic-title">AIORPG</span>

        </div>
        <!-- 导航栏 -->
        <a-menu
            mode="horizontal"
            :default-selected-keys="['home']"
            class="navbar-menu"
        >
          <a-menu-item key="home" @click="goToHome">首页</a-menu-item>
          <a-menu-item key="playscript" @click="goToPlayScript">剧本</a-menu-item>
          <a-menu-item key="game" @click="goToArchive">存档</a-menu-item>
          <a-menu-item key="administer" v-if="isLoggedIn && userInfo.role === 'admin'" @click="goToAdmin">管理员</a-menu-item>
        </a-menu>
        <!-- 右侧导航菜单 -->
        <div class="navbar-right" @click="toggleCard">
        <template v-if="isLoggedIn">
          <!-- 用户头像和用户名 -->
          <div class="avatar-wrapper">
            <img :src="userInfo.avatar || defaultAvatar" alt="头像" class="avatar" />
            <span class="username">{{ userInfo.username || '未登录' }}</span>
          </div>
          <div
              v-if="showCard"
              class="profile-card"
              @mouseenter="handleMouseEnter"
              @mouseleave="handleMouseLeave"
          >
            <img :src="userInfo.avatar || defaultAvatar" alt="头像" class="large-avatar" />
            <p class="username">{{ userInfo.username }}</p>
            <p class="email">{{ userInfo.email || '未设置邮箱' }}</p>
            <ul>
              <li @click="changeAvatar">修改头像</li>
              <li @click="changeUsername">修改昵称</li>
              <li @click="changePassword">修改密码</li>
              <li @click="logout">退出登录</li>
            </ul>
          </div>
        </template>
        <template v-else>
          <a-button type="primary" class="navbar-button" @click="goToLogin">登录</a-button>
          <a-button type="primary" class="navbar-button" @click="goToRegister">注册</a-button>
        </template>
      </div>
      </a-layout-header>
    </a-layout>
</template>

<script>
import {userInfoService} from "@/api/user";
import defaultAvatar from "@/assets/default-avatar.png"
import request from "@/utils/request";

export default {
  name: 'Navbar',
  data() {
    return {
      userInfo: {
        id: '',
        username: '',
        avatar: '',
        email: '',
        role: 'user'
      },
      isLoggedIn: false,
      showCard: false,
      defaultAvatar: defaultAvatar,

    }
  },
  mounted() {
    this.checkLoginStatus();
  },
  methods: {
    handleMouseEnter() {
      this.showCard = true;
    },
    handleMouseLeave() {
      this.isMouseOverCard = false;
      setTimeout(() => {
        if (!this.isMouseOverCard) {
          this.showCard = false;
        }
      }, 200);
    },
    goToHome() {
      this.$router.push('/');
    },
    goToPlayScript() {
      this.$router.push('/AIOPlayScript');
    },
    goToLogin() {
      this.$router.push('/AIOLogin');
    },
    goToRegister() {
      this.$router.push('/AIORegister');
    },
    goToArchive() {
      this.$router.push('/AIOArchive');
    },
    goToAdmin() {
      this.$router.push('/AIOAdmin');
    },
    logout() {
      localStorage.clear();
      this.isLoggedIn = false;
      this.userInfo = {id: '', username: '', avatar: '' , role: 'user',email: '' };
      this.$router.push('/');
    },
    async checkLoginStatus() {
      let token = localStorage.getItem('token');
      if (!token) {
        this.isLoggedIn = false;
        this.userInfo = {id: '', username: '', avatar: '', role: 'user',email: '' };
        localStorage.clear();
        return;
      }
      if (!this.isLoggedIn) {
        this.isLoggedIn = true;
        await this.fetchUserInfo();
      }
    },
    async fetchUserInfo() {
      try {
        const result = await userInfoService();
        if (result && result.code === "0" && result.data) {
          this.userInfo.id = result.data.id;
          this.userInfo.username = result.data.username;
          this.userInfo.role = result.data.role;
          this.userInfo.email = result.data.email;
          if (result.data.avatar) {
            try {
              // 使用 request 工具类请求头像
              const response = await request.get(result.data.avatar, {
                responseType: "blob"
              });
              // 将 Blob 数据转换为 URL
              this.userInfo.avatar = URL.createObjectURL(response);
            } catch (error) {
              console.error("Failed to load avatar image:", error);
              this.userInfo.avatar = '';
            }
          }
          //存储到 localStorage
          const { id, username, avatar, role } = result.data;
          const info = { id, username, avatar, role };
          localStorage.setItem('userInfo', JSON.stringify(info));
        } else {
          alert('读取用户信息失败！请刷新重试！');
          console.error(result.message);
          this.isLoggedIn = false;
        }
      } catch (error) {
        console.error("Error fetching user info:", error);
        alert('读取用户信息失败！请刷新重试！');
        this.isLoggedIn = false;
      }
    },
    toggleCard() {
      if(!this.isLoggedIn) {
        return;
      }
      this.showCard = !this.showCard;
    },

    changeAvatar() {
      this.$router.push({ path: '/AIOPersonCenter', query: { action: 'changeAvatar' } });
    },
    changeUsername() {
      this.$router.push({ path: '/AIOPersonCenter', query: { action: 'changeUsername' } });
    },
    changePassword() {
      this.$router.push({ path: '/AIOPersonCenter', query: { action: 'changePassword' } });
    }



  }
}
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: rgba(255, 255, 255, 0.5); /* 半透明效果 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: fixed; /* 固定在顶部 */
  width: 100%;
  z-index: 10;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  color: #ffffff;
}

.logo img {
  height: 32px;
  margin-right: 8px;
}

.navbar-menu {
  flex-grow: 1;
  display: flex;
  justify-content: flex-start; /* 菜单靠右对齐 */
  align-items: center;
  background-color: transparent; /* 去除菜单背景 */
  border-bottom: none; /* 去除底部边框 */
  padding: 0 30px
}

.ant-menu-item {
  padding: 0 30px; /* 增加菜单项之间的间距 */
  font-weight: 500;
  color: #000;
  cursor: pointer;
}

.artistic-title {
  font-size: 36px;
  font-weight: bold;
  font-family: 'Cinzel', serif;
  background: linear-gradient(45deg, #ffffff, #f8d800);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.5);
  letter-spacing: 2px;
  margin: 0 10px;
  cursor: pointer;
  transition: transform 0.2s ease-in-out;
}

.artistic-title:hover {
  transform: scale(1.1);
}
.navbar-menu li {
  list-style: none;
}
.navbar-menu a {
  color: #fff;
  text-decoration: none;
}
.navbar-right {
  display: flex;
  align-items: center;
  gap: 15px;
}
.navbar-button {
  display: flex;
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #ffcd00;
  color: #000;
  align-items: center
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  margin-right: 10px
}

.profile-card {
  position: absolute;
  top: 100px;
  right: 15px;
  width: 200px;
  background-color: #272c30;
  border-radius: 8px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
  padding: 15px;
  text-align: center;
  z-index: 100;
}

.large-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  margin-bottom: 20px;
}

.username {
  cursor: pointer;
  font-weight: 500;
  color: #ffcd00;
  font-size: 22px;
}

.username, .email, .reserve {
  margin: 10px 0;
  color: #ffcd00;
}

.profile-card ul {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}

.profile-card ul li {
  padding: 5px 10px;
  margin: 0;
  color: #ffffff;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.profile-card ul li:hover {
  background-color: #007bff;
  border-radius: 5px;
}
.avatar-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
}

</style>
